package com.commerceerp.system.service;

import com.commerceerp.system.api.winit.TokenTest;
import com.commerceerp.system.api.winit.WinitUtil;
import com.commerceerp.system.api.winit.model.FreightInfo;
import com.commerceerp.system.api.winit.model.OutboundOrder;
import com.commerceerp.system.api.winit.model.Product;
import com.commerceerp.system.entity.LogisticsWinit;
import com.commerceerp.system.mapper.OrderMapper;
import com.commerceerp.system.mapper.WinitMapper;
import com.commerceerp.system.util.ApiResult;
import com.commerceerp.system.util.StringUtils;
import com.google.common.collect.Lists;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WinitService {

    @Autowired
    private WinitMapper winitMapper;

    @Autowired
    private OrderMapper orderMapper;

    //万邑通物流编辑
    public ApiResult form(LogisticsWinit logisticsWinit) {
        logisticsWinit.insert();
        String token = TokenTest.getTokenByAccount(logisticsWinit.getUsername(),logisticsWinit.getPassword());
        if(StringUtils.isEmpty(token)){
            return new ApiResult(405,"万邑通账号密码有误，请确认后再尝试");
        }
        logisticsWinit.setToken(token);
        winitMapper.insert(logisticsWinit);
        return new ApiResult(200,"编辑成功");
    }

    //获得仓库列表
    public ApiResult getWarehouse(){

        return new ApiResult(winitMapper.getWarehouse());
    }

    //同步仓库和配送方式列表
    public void addWarehouse(){
        WinitUtil w = new WinitUtil();
        String result = w.queryWarehouse();
        JSONObject json = JSONObject.fromObject(result);
        String code = json.getString("code");
        if(StringUtils.equals(code,"0")){
            JSONArray list  = json.getJSONArray("data");
            for(int i = 0;i<list.size();i++){
                JSONObject child = list.getJSONObject(i);
                String dresult = w.queryDeliveryWay(child.getString("warehouseID"));
                JSONObject djson = JSONObject.fromObject(dresult);
                String dcode = djson.getString("code");
                if(StringUtils.equals(dcode,"0")){
                    //删除原有的配送方式
                    winitMapper.delDeliveryWay(child.getString("warehouseID"));
                    if(djson.getJSONArray("data").size() > 0){
                        //保存配送方式
                        winitMapper.saveDeliveryWay(djson.getJSONArray("data"));
                    }
                }
                //保存仓库
                winitMapper.saveWarehouse(child);
            }
        }
    }

    //删除万邑联授权码
    public ApiResult delWinitToken(String id, String userId) {
        winitMapper.delWinitToken(id,userId);
        return new ApiResult(200,"删除授权成功");
    }

    //仓库库存信息
    public ApiResult getStock(String warehouseId, String sku, String userId) {
        LogisticsWinit logisticsWinit = winitMapper.getLogisticsWinitByUserId(userId);
        String token = TokenTest.getTokenByAccount(logisticsWinit.getUsername(),logisticsWinit.getPassword());
        if(StringUtils.isEmpty(token)){
            return new ApiResult(405,"万邑通账号密码有误，请确认后再尝试");
        }
        WinitUtil w = new WinitUtil();
        if(StringUtils.isNotEmpty(warehouseId)){//确定仓库
            String result = "";
            if(StringUtils.isEmpty(sku)){//确定产品code
                result = w.queryWarehouseStorage(warehouseId,token);
            }else{
                result =  w.queryProductInventoryDetail(sku,warehouseId,token);
            }
            JSONObject json = JSONObject.fromObject(result);
            String code = json.getString("code");
            if(StringUtils.equals(code,"0")){
                JSONObject data = json.optJSONObject("data");
                return new ApiResult(data.getJSONArray("list"));
            }
        }else{
            warehouseId = "";
            String result = w.queryWarehouse();
            JSONObject json = JSONObject.fromObject(result);
            String code = json.getString("code");
            if(StringUtils.equals(code,"0")) {
                List<Map> list = winitMapper.getWarehouse();
                for (int i = 0; i < list.size(); i++) {
                    Map child = list.get(i);
                    if(i > 0){
                        warehouseId += ",";
                    }
                    warehouseId += child.get("warehouseId");
                }
                result =  w.queryProductInventoryDetail(sku,warehouseId,token);
                JSONObject json2 = JSONObject.fromObject(result);
                String code2 = json2.getString("code");
                if(StringUtils.equals(code2,"0")){
                    JSONObject data2 = json2.optJSONObject("data");
                    return new ApiResult(data2.getJSONArray("list"));
                }
            }
        }
        return new ApiResult(405,"没有数据");
    }

    //运费信息
    public ApiResult getFreight(String orderId, String userId,String country,String region,String city, String zipCode) {
        List<FreightInfo> datas = Lists.newArrayList();
        LogisticsWinit logisticsWinit = winitMapper.getLogisticsWinitByUserId(userId);
        String token = TokenTest.getTokenByAccount(logisticsWinit.getUsername(),logisticsWinit.getPassword());
        if(StringUtils.isEmpty(token)){
            return new ApiResult(405,"万邑通账号密码有误，请确认后再尝试");
        }
        List<Map> orderGoods = orderMapper.getGoodInfosByOrderId(orderId);
        List<Product> productList = new ArrayList<Product>();
        for(Map good : orderGoods){
            Product pd = new Product();
            pd.setProductCode((String) good.get("goodPlatformSku"));
            pd.setProductNum(good.get("orderGoodNumber") + "");
            pd.setSpecification((String) good.get("specification"));
            productList.add(pd);
        }

        WinitUtil w = new WinitUtil();
        //获得配送方式信息
        List<Map> list = winitMapper.getDeliveryWay();
        for (int i = 0; i < list.size(); i++) {
            Map child = list.get(i);
            //获得各种模式配送费用
            String fres = w.queryDeliveryFee(productList,(String)child.get("warehouseCode"),(String)child.get("winitProductCode"),country,region,city,zipCode,token);
            JSONObject fjson = JSONObject.fromObject(fres);
            String fcode = fjson.getString("code");
            if(StringUtils.equals(fcode,"0")) {
                JSONArray flist = fjson.getJSONArray("data");
                for (int j = 0; j < flist.size(); j++) {
                    JSONObject fchild = flist.getJSONObject(j);
                    FreightInfo freightInfo = new FreightInfo();
                    freightInfo.setWarehouseId((String)child.get("warehouseId"));
                    freightInfo.setWarehouseName((String)child.get("warehouseName"));
                    freightInfo.setDeliveryWay(fchild.getString("deliveryWay"));
                    freightInfo.setDeliveryID((String)child.get("deliveryID"));
                    freightInfo.setISOCode(fchild.getString("ISOCode"));
                    freightInfo.setTotalFeeUSD(fchild.getDouble("totalFeeUSD"));
                    freightInfo.setOutboundMethod(fchild.getString("outboundMethod"));
                    freightInfo.setLogisticsTime(fchild.getInt("logisticsTime"));
                    datas.add(freightInfo);
                }
            }
        }
        ListSort(datas);
        return new ApiResult(datas);
    }

    //排序
    private static void ListSort(List<FreightInfo> list) {
        Collections.sort(list, new Comparator<FreightInfo>() {
            @Override
            public int compare(FreightInfo o1, FreightInfo o2) {
                try {
                    double dt1 = o1.getTotalFeeUSD();
                    double dt2 = o2.getTotalFeeUSD();
                    if (dt1 > dt2) {
                        return 1;
                    } else if (dt1 < dt2) {
                        return -1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }

    //创建出库单
    public ApiResult createOutboundOrder(OutboundOrder outboundOrder, String userId) {
        LogisticsWinit logisticsWinit = winitMapper.getLogisticsWinitByUserId(userId);
        String token = TokenTest.getTokenByAccount(logisticsWinit.getUsername(),logisticsWinit.getPassword());
        if(StringUtils.isEmpty(token)){
            return new ApiResult(405,"万邑通账号密码有误，请确认后再尝试");
        }
        WinitUtil w = new WinitUtil();
        List<Map> orderGoods = orderMapper.getGoodInfosByOrderId(outboundOrder.getOrderId());
        JSONArray productList = new JSONArray();
        for(Map good : orderGoods){
            com.alibaba.fastjson.JSONObject product = new com.alibaba.fastjson.JSONObject();
            product.put("eBayBuyerID",null);
            product.put("eBayItemID",null);
            product.put("eBaySellerID",null);
            product.put("eBayTransactionID",null);
            product.put("productCode",good.get("goodPlatformSku"));
            product.put("productNum",good.get("orderGoodNumber"));
            product.put("specification",good.get("specification"));
            productList.add(product);
        }
        String result = w.createOutboundOrder(outboundOrder,productList,token);
        JSONObject json = JSONObject.fromObject(result);
        String code = json.getString("code");
        if(StringUtils.equals(code,"0")) {
            JSONObject data = json.optJSONObject("data");
            //出库单号
            String outboundOrderNum = data.getString("outboundOrderNum");
            outboundOrder.setOutboundOrderNum(outboundOrderNum);
            outboundOrder.setLogisticType("0");
            //修改订单
            orderMapper.updateOrderByOut(outboundOrder);
            return new ApiResult(outboundOrderNum);
        }
        return new ApiResult(json);
    }
}
